'use strict'

module.exports = angular.module('lib.directives.datetimepicker', [])
.provider 'datetimepicker', ->
  $log.log "datetimepicker.log"
  now = new Date()
  default_options =
    format: 'YYYY-MM-DD HH:mm'
    locale: 'zh-cn'
    timeZone: 'Asia/Shanghai'
    defaultDate : now
  @setOptions = (options)->
    default_options = options

  @$get = ->
    getOptions : ->
      default_options

  return

.directive 'datetimepicker', ['$timeout', 'datetimepicker',($timeout,datetimepicker)->
  default_options = datetimepicker.getOptions()
  require : '?ngModel'
  restrict: 'AE'
  scope   :
    datetimepickerOptions: '@'
    restrict: '@'
    linked: '@'
  link : ($scope, $element, $attrs, ngModelCtrl)->


    passed_in_options = $scope.$eval $attrs.datetimepickerOptions
    options = jQuery.extend {}, default_options, passed_in_options
    $element
    .on 'dp.change', (e)->
      if ngModelCtrl
        $timeout ->
          ngModelCtrl.$setViewValue e.target.value

      if $attrs.restrict is 'begin'
        $timeout ->
          $element.data("DateTimePicker").minDate(default_options.defaultDate)
          $('#'+$attrs.linked).data("DateTimePicker").minDate(e.date)

    .datetimepicker options


    setPickerValue = ->
      date = null
      if ngModelCtrl and ngModelCtrl.$viewValue
        date = ngModelCtrl.$viewValue

      console.log date
      $element.data('DateTimePicker').date(date)

    if ngModelCtrl
      ngModelCtrl.$render = ->
        setPickerValue()

    setPickerValue()
]
